<template>
  <el-dialog v-model="props.showDia" :title="props.title + 'banner'" width="30%" center :show-close="false" :close-on-press-escape="false" :close-on-click-modal="false">
    <el-form
                label-position="top"
                ref="ruleFormRef"
                label-width="100px"
                :rules="rules"
                :model="data"
                style="max-width: 460px; margin-left: 10%;"
                class="login_form"
                scroll-to-error="true"
                size="large"
            >
                <el-form-item class="label" label="商品图片：" prop="g_img">
                  <template #default="scope">
                        <el-upload
                        class="avatar-uploader"
                        :action="action"
                        :show-file-list="false"
                        :headers="headders"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        >
                            <img v-if="imageUrl != '' " :src="imageUrl" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </template>
                </el-form-item>
                <el-form-item class="label" label="优先级：" prop="g_name">
                    <el-input v-model="data.banner_name" />
                </el-form-item>
            </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="ok(ruleFormRef)">提交</el-button>
        <el-button type="primary" @click="esc(ruleFormRef)">
          取消
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {ref,watch, reactive, onMounted} from "vue"
import type { FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {bannerListOneApi, bannerUpdatListApi, bannerAddListApi} from "../composables/http"
import type { UploadProps, UploadUserFile } from 'element-plus'

import { ElMessage } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
const headders = ref()
const props = defineProps({
    showDia:{
        type:Boolean,
        default:false
    },
    nid:{
        type:Number,
        default:null
    },
    title:{
        type:String,
        required:true
    }
})

const rules = reactive<FormRules<typeof data>>({
    banner_name: [
        { required: true, message: '请输入优先级', trigger: 'blur' },
    ],
    banner_img: [{ required: true, message: '请上传Banner图片', trigger: 'blur'  }],
})
const data = reactive<{
    banner_id:string
    banner_img:string
    banner_name:number
}>({
  banner_id:'',
  banner_img:"",
  banner_name: 0,
})


const fileList = ref<UploadUserFile[]>([
])

const action = ref("")
onMounted(()=>{
    if (props.title == "修改"){
      dataList()
    }
    action.value =`http://127.0.0.1:8000/admin/${props.nid}/avatar`
})
const emit = defineEmits(["showDiaf","showusername"]);
const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
    if (response.code == 200){
      imageUrl.value = response.data
      data.banner_img = response.data
    }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  headders.value = {"Authorization" :  localStorage.getItem('d_token')}
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const dataList = async()=>{
    const d = await bannerListOneApi(props.nid)
    if(d.code==200){
      data.banner_img = d.data.banner_img
      data.banner_name = d.data.banner_name
      imageUrl.value = d.data.banner_img
    }
}
const ok = (formEl: FormInstance | undefined)=>{
    if (!formEl) return
    formEl.validate(async(valid) => {
    if (valid) {
      const d = props.title == "添加" ? await bannerAddListApi(data) : await bannerUpdatListApi(props.nid, data)
      if(d.code == 200){
        emit("showusername","")
        emit("showDiaf",false)
        fileList.value = []
      }
    } else {
      console.log('验证失败!')
      return false
    }
  })
}
const esc = (formEl: FormInstance | undefined)=>{
    emit("showusername","")
    emit("showDiaf",false)
    fileList.value = []
    
}

</script>


<style lang='scss' scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

:deep .el-form-item__content{
    justify-content: center;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>